package com.dieusoft.box.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dieusoft.box.ship.entity.ShipExport;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;
import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;
import org.jeecg.common.util.DateUtils;
import org.springframework.stereotype.Component;

import java.io.FileOutputStream;
import java.io.IOException;


/**
 * 这个工具类用于测试PDF的非模板导出，和多页使用一个模板
 */
@Component
public class DownPdf {


    /**
     * 用pdf模板生成多条内容
     */
    public static void fillTemplateByDcwts(ShipExport shipExport, String newPDFPath, String templatePath) {
        FileOutputStream out;
        try {
            out = new FileOutputStream(newPDFPath);// 输出流
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();

            // int count=0;
            PdfReader reader = new PdfReader(templatePath);// 读取pdf模板
            ByteArrayOutputStream bos;
            PdfStamper stamper;
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();
            form.setField("consignor", shipExport.getConsignor());
            form.setField("consignee", shipExport.getConsignee());
            form.setField("notifier", shipExport.getNotifier());
            form.setField("customerNumber", shipExport.getCustomerNumber());
            form.setField("shipCompany", shipExport.getShipCompany());
            form.setField("operator", shipExport.getOperator());
            form.setField("destination", shipExport.getDestination());
            form.setField("shipName", shipExport.getShipName());
            form.setField("voyageNumber", shipExport.getVoyageNumber());
            form.setField("portDeparture", shipExport.getPortDeparture());
            form.setField("portDestination", shipExport.getPortDestination());
            form.setField("placeDelivery", shipExport.getPlaceDelivery());
            form.setField("tradeClause", shipExport.getTradeClause());
            form.setField("payType", shipExport.getPayType());
            form.setField("shipMarks", shipExport.getShipMarks());
            form.setField("total", shipExport.getTotal());
            form.setField("totalGrossWeight", shipExport.getTotalGrossWeight());
            form.setField("totalVolume", shipExport.getTotalVolume());

            stamper.setFormFlattening(true);
            stamper.close();
            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            PdfImportedPage importPage1 = copy.getImportedPage(new PdfReader(bos.toByteArray()), 2);
            copy.addPage(importPage);
            copy.addPage(importPage1);
            doc.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    /**
     * 用pdf模板生成多条内容
     */
    public static void fillTemplateByRhtzs(JSONObject shipExport, String newPDFPath, String templatePath) {
        FileOutputStream out;
        try {
            out = new FileOutputStream(newPDFPath);// 输出流
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();

            // int count=0;
            PdfReader reader = new PdfReader(templatePath);// 读取pdf模板
            ByteArrayOutputStream bos;
            PdfStamper stamper;
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();
            JSONObject boxInfo = JSONObject.parseObject(shipExport.getString("boxInfo"));
            //件重尺
            String pieceNumber = boxInfo.getString("pieceNumber");
            String totalWeight = boxInfo.getString("totalWeight");
            String totalVolume = boxInfo.getString("totalVolume");
            String pieceNumberUnit = boxInfo.getString("pieceNumberUnit");
            StringBuilder sbJcz = new StringBuilder();
            sbJcz.append(pieceNumber).append(pieceNumberUnit).append("/")
                    .append(totalWeight).append(" KGS/")
                    .append(totalVolume).append(" CBM");

            JSONArray boxList = JSONObject.parseArray(boxInfo.getString("boxList"));
            StringBuilder sbBox = new StringBuilder();
            for (int i = 0; i < boxList.size(); i++) {
                JSONObject boxItem = JSONObject.parseObject(boxList.get(i).toString());
                sbBox.append(boxItem.getString("boxtype")).append("*").append(boxItem.getString("boxl")).append(",");
            }
            form.setField("today", DateUtils.formatDate());
            form.setField("jcz", sbJcz.toString());
            form.setField("box", sbBox.toString());
            form.setField("shipName", shipExport.getString("shipName") + "/" + shipExport.getString("voyageNumber"));
            form.setField("entrustCompany", shipExport.getString("entrustCompany_dictText"));

            form.setField("operator", shipExport.getString("operator"));
            form.setField("mainOffNumber", shipExport.getString("mainOffNumber").replaceAll("\\[","").replaceAll("]","").replaceAll("\"",""));
            form.setField("portDeparture", shipExport.getString("portDeparture"));
            form.setField("portDestination", shipExport.getString("portDestination"));
            form.setField("placeDelivery", shipExport.getString("placeDelivery"));
            form.setField("cutOffTime", shipExport.getString("cutOffTime"));
            form.setField("station", shipExport.getString("station"));
            form.setField("shipCompany", shipExport.getString("shipCompany"));

            stamper.setFormFlattening(true);
            stamper.close();
            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage);
            doc.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    /**
     * 用pdf模板生成多条内容
     */
    public static void fillTemplateByDfbh(JSONObject shipExport, String newPDFPath, String templatePath) {
        FileOutputStream out;
        try {
            out = new FileOutputStream(newPDFPath);// 输出流
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();

            // int count=0;
            PdfReader reader = new PdfReader(templatePath);// 读取pdf模板
            ByteArrayOutputStream bos;
            PdfStamper stamper;
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();
            JSONObject jsonObject = JSONObject.parseObject(shipExport.toString());
            JSONObject boxInfo = JSONObject.parseObject(jsonObject.getString("boxInfo"));
            //件重尺
            String pieceNumber = boxInfo.getString("pieceNumber");
            String totalWeight = boxInfo.getString("totalWeight");
            String totalVolume = boxInfo.getString("totalVolume");
            String pieceNumberUnit = boxInfo.getString("pieceNumberUnit");
            StringBuilder sbJcz = new StringBuilder();
            sbJcz.append(pieceNumber).append(pieceNumberUnit).append("/")
                    .append(totalWeight).append(" KGS/")
                    .append(totalVolume).append(" CBM");
            form.setField("today", DateUtils.formatDate());
            form.setField("jcz", sbJcz.toString());
            form.setField("portDepartureANDplaceDelivery", jsonObject.getString("portDeparture") + "/" + jsonObject.getString("placeDelivery"));
            form.setField("shipName", jsonObject.getString("shipName") + "/" + jsonObject.getString("voyageNumber"));

            form.setField("consignor", shipExport.getString("consignor"));
            form.setField("consignee", shipExport.getString("consignee"));
            form.setField("mainOffNumber", shipExport.getString("mainOffNumber").replaceAll("\\[","").replaceAll("]","").replaceAll("\"",""));
            form.setField("otherOffNumber", shipExport.getString("otherOffNumber").replaceAll("\\[","").replaceAll("]","").replaceAll("\"",""));
            form.setField("enName", shipExport.getString("enName"));


            stamper.setFormFlattening(true);
            stamper.close();
            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage);
            doc.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
    /**
     * 该方法用于非模板的导出PDF 里面可以调用下面的一些方法做测试，生成需要的文字，表格等
     * @param filename
     * @param products
     * @throws IOException
     * @throws DocumentException
     */
//    public static void createPDF(String filename, List<Product> products) throws IOException, DocumentException {
//        Document document = new Document(PageSize.A4);
//        //下面的结果没有生效 中文文字没出来
//        Font font = new Font(BaseFont.createFont("C://Windows//Fonts//simfang.ttf", BaseFont.IDENTITY_H,
//                BaseFont.NOT_EMBEDDED));
//        try {
//            PdfWriter.getInstance(document, new FileOutputStream(filename));
//            document.addTitle("example of PDF");
//            document.open();
//            Paragraph p = new Paragraph("Hello World!");
//            p.setAlignment(Element.ALIGN_CENTER);
//            document.add(p);
//            p = new Paragraph("小川测试打印输出产品信息表文字",font);
//            p.setAlignment(Element.ALIGN_CENTER);
//            document.add(p);
//            document.add(new Paragraph("开始",font));
//            //插入段落
//            p = new Paragraph("iText 是一个非常著名的能够快速产生 PDF 文件的 Java 类库。支持文本，表格，图形的操作，可以方便的跟 Servlet 进行结合。",font);
//            //设置首行缩进
//            p.setFirstLineIndent(14);
//            //设置段落居中对齐
//            p.setAlignment(Element.ALIGN_JUSTIFIED);
//            p.setIndentationLeft(1 * 15f);
//            p.setIndentationRight((5 - 1) * 15f);
//
//            document.add(p);
//            document.add(Chunk.NEWLINE);
//            PdfPTable table = createTable(products);
//            document.add(table);
//            document.add(new Paragraph("Hello World!"));
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (DocumentException e) {
//            e.printStackTrace();
//        } finally {
//            document.close();
//        }
//    }

    /**
     *测试  此方法用于生成表格及填充里面的文字
     * @param products
     * @return PdfPTable
     * @throws IOException
     * @throws DocumentException
     */
//    public static PdfPTable createTable( List<Product> products) throws IOException, DocumentException {
//        PdfPTable table = new PdfPTable(4);//生成一个 4列的表格
//        //下面字体为windows自带的字体 在linux下可能会失效
//        Font font = new Font(BaseFont.createFont("C://Windows//Fonts//simfang.ttf", BaseFont.IDENTITY_H,
//                BaseFont.NOT_EMBEDDED));
//        //使用itext-asian.jar中的中文字体 版本5.0.6好像会出问题，改成5.4.3就解决了
//        //Font font = new Font(BaseFont.createFont( "STSongStd-Light" ,"UniGB-UCS2-H",BaseFont.NOT_EMBEDDED));
//
//        //使用自己下载的资源字体。在项目内，这种方法可以说是最麻烦的，但是也是最有效的。麻烦是因为自己要去下载字体文件，但是效果确是最好的，能够应对各种系统，各种状况
//        //Font font = new Font(BaseFont.createFont( "/simsun.ttf",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED));
//
//        int headerwidths[] = { 10, 10, 10, 10}; // percentage
//        table.setWidths(headerwidths);
//        table.setWidthPercentage(100);
//        table.getDefaultCell().setPadding(3);
//        table.getDefaultCell().setBorderWidth(3);
//        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
//
//
//        table.addCell(new PdfPCell(new Phrase("产品编号",font)));
//        table.addCell(new PdfPCell(new Phrase("产品供应商",font)));
//        table.addCell(new PdfPCell(new Phrase("产品价格",font)));
//        table.addCell(new PdfPCell(new Phrase("产品数量",font)));
//
//        PdfPCell cell;
//        int size = 20;
//
//
//        for(int i = 0;i<products.size();i++) {
//            cell = new PdfPCell(new Phrase(products.get(i).getType(),font));//产品编号
//            cell.setFixedHeight(size); //设置高度
//            table.addCell(cell);
//            cell = new PdfPCell(new Phrase(products.get(i).getProvider(),font));//产品供应商
//            cell.setFixedHeight(size);
//            table.addCell(cell);
//            cell = new PdfPCell(new Phrase(products.get(i).getPrice()+"",font));//产品价格
//            cell.setFixedHeight(size);
//            table.addCell(cell);
//            cell = new PdfPCell(new Phrase(products.get(i).getAmount()+"",font));//产品数量
//            cell.setFixedHeight(size);
//            table.addCell(cell);
//
//        }
//
//        //循环开始前 所有产品表都打印完毕 接下来输出后面的文字，用表格填充
//        cell = new PdfPCell(new Phrase("产品详情清单结束",font));
//        cell.setFixedHeight(size*2);//设置高度
//        cell.setColspan(4);//设置所占列数
//        cell.setRowspan(2);//合并行
//        cell.setHorizontalAlignment(Element.ALIGN_CENTER);//设置水平居中
//        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置垂直居中
//        table.addCell(cell);
//
//        return table;
//    }

    /**
     * 测试  此方法用于生成 Chunk对象 Phrase对象 Paragraph对象 举例
     * @param document
     * @throws DocumentException
     */
//    public static void createChunkPhraseParagraphExample(Document document) throws DocumentException {
//        //Chunk对象: a String, a Font, and some attributes
//        document.add(new Chunk("China"));
//        document.add(new Chunk(" "));
//        Font font = new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE);
//        Chunk id = new Chunk("chinese", font);
//        id.setBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f);
//        id.setTextRise(6);
//        document.add(id);
//        document.add(Chunk.NEWLINE);
//
//        document.add(new Chunk("Japan"));
//        document.add(new Chunk(" "));
//        Font font2 = new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE);
//        Chunk id2 = new Chunk("japanese", font2);
//        id2.setBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f);
//        id2.setTextRise(6);
//        id2.setUnderline(0.2f, -2f);
//        document.add(id2);
//        document.add(Chunk.NEWLINE);
//
//        //Phrase对象: a List of Chunks with leading
//        document.newPage();
//        document.add(new Phrase("Phrase page"));
//
//        Phrase director = new Phrase();
//        Chunk name = new Chunk("China");
//        name.setUnderline(0.2f, -2f);
//        director.add(name);
//        director.add(new Chunk(","));
//        director.add(new Chunk(" "));
//        director.add(new Chunk("chinese"));
//        director.setLeading(24);
//        document.add(director);
//
//        Phrase director2 = new Phrase();
//        Chunk name2 = new Chunk("Japan");
//        name2.setUnderline(0.2f, -2f);
//        director2.add(name2);
//        director2.add(new Chunk(","));
//        director2.add(new Chunk(" "));
//        director2.add(new Chunk("japanese"));
//        director2.setLeading(24);
//        document.add(director2);
//
//        //Paragraph对象: a Phrase with extra properties and a newline
//        document.newPage();
//        document.add(new Paragraph("Paragraph page"));
//
//        Paragraph info = new Paragraph();
//        info.add(new Chunk("China "));
//        info.add(new Chunk("chinese"));
//        //换行
//        info.add(Chunk.NEWLINE);
//        info.add(new Phrase("Japan "));
//        info.add(new Phrase("japanese"));
//        document.add(info);
//
//        //List对象: a sequence of Paragraphs called ListItem
////        document.newPage();
////        List list = new List(List.ORDERED);
////        for (int i = 0; i < 10; i++) {
////            ListItem item = new ListItem(String.format("%s: %d movies",
////                    "country" + (i + 1), (i + 1) * 100), new Font(
////                    Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE));
////            List movielist = new List(List.ORDERED, List.ALPHABETICAL);
////            movielist.setLowercase(List.LOWERCASE);
////            for (int j = 0; j < 5; j++) {
////                ListItem movieitem = new ListItem("Title" + (j + 1));
////                List directorlist = new List(List.UNORDERED);
////                for (int k = 0; k < 3; k++) {
////                    directorlist.add(String.format("%s, %s", "Name1" + (k + 1),
////                            "Name2" + (k + 1)));
////                }
////                movieitem.add(directorlist);
////                movielist.add(movieitem);
////            }
////            item.add(movielist);
////            list.add(item);
////        }
////        document.add(list);
//    }

    /**
     * 测试  此方法用于生成测试的段落及一些小的细节注释，测试打印表头帮助学习PDF生成文字等
     * @param document
     * @throws DocumentException
     * @throws IOException
     */
//    public static void createExample(Document document) throws DocumentException, IOException {
//
//
//        Font font = new Font(BaseFont.createFont("C://Windows//Fonts//simfang.ttf", BaseFont.IDENTITY_H,
//                BaseFont.NOT_EMBEDDED));
//        //添加段落
//        document.add(new Paragraph("Hello World!"));
//        document.add(new Paragraph("Hello World!"));
//        //设置换行
//        document.add(Chunk.NEWLINE);
//        document.add(new Paragraph("Hello World!"));
//        document.add(new Paragraph("小川测试打印输出产品信息表文字",font));
//
//        //插入段落
//        Paragraph p = new Paragraph("In the previous example, you added a header and footer with the showTextAligned() method. This example demonstrates that it’s sometimes more interesting to use PdfPTable and writeSelectedRows(). You can define a bottom border for each cell so that the header is underlined. This is the most elegant way to add headers and footers, because the table mechanism allows you to position and align lines, images, and text.");
//        p.setFirstLineIndent(14);
//
//        //设置对齐 默认
//        p.setAlignment(Element.ALIGN_JUSTIFIED);
//        document.add(p);
//
//        //分页
//        document.newPage();
//        p.setAlignment(Element.ALIGN_JUSTIFIED);
//        p.setIndentationLeft(1 * 15f);
//        p.setIndentationRight((5 - 1) * 15f);
//
//        document.add(p);
//        //设置换行
//        document.add(Chunk.NEWLINE);
//
//
//
//        //测试打印表头
//        String[] bogusData = { "M0065920", "SL", "FR86000P", "PCGOLD",
//                "119000", "96 06", "2001-08-13", "4350", "6011648299",
//                "FLFLMTGP", "153", "119000.00" };
//        int NumColumns = 12;
//        // 12
//        PdfPTable datatable = new PdfPTable(NumColumns);
//        int headerwidths[] = { 9, 4, 8, 10, 8, 11, 9, 7, 9, 10, 4, 10 }; // percentage
//        datatable.setWidths(headerwidths);
//        datatable.setWidthPercentage(100);
//        datatable.getDefaultCell().setPadding(3);
//        datatable.getDefaultCell().setBorderWidth(2);
//        datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
//
//
//        datatable.addCell(new PdfPCell(new Phrase("型号",font)));
//        datatable.addCell("hah");
//        datatable.addCell("xixi");
//        datatable.addCell("ehhe");
//        datatable.addCell("prod");
//        datatable.addCell("dehd wejdrh");
//        datatable.addCell("Settle Date");
//        datatable.addCell("Portfolio");
//        datatable.addCell("ADP Number");
//        datatable.addCell("Account ID");
//        datatable.addCell("Reg Rep ID");
//        datatable.addCell("Amt To Go ");
//
//        datatable.setHeaderRows(1);
//
//        //边框
//        datatable.getDefaultCell().setBorderWidth(1);
//
//        //插入数据
//        for (int i = 1; i < 10; i++) {
//            for (int x = 0; x < NumColumns; x++) {
//                datatable.addCell(bogusData[x]);
//            }
//        }
//
//        document.add(datatable);
//
//    }
}
